/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.nmpp.commons;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import cn.ac.iie.di.ban.nmpp.config.Configuration;
import cn.ac.iie.di.ban.nmpp.metastore.MetaStoreManager;
import cn.ac.iie.di.ban.nmpp.metastore.Table2MQRule;
import cn.ac.iie.di.datadock.rdata.exchange.client.core.REFieldType;
import cn.ac.iie.di.datadock.rdata.exchange.client.exception.REConnectionException;
import cn.ac.iie.di.datadock.rdata.exchange.client.exception.RESessionException;
import com.alibaba.fastjson.JSONObject;

public class RuntimeEnv {
    
    private static Configuration conf = null;
    private static Map<String, Object> dynamicParams = new HashMap<String, Object>();
    public static final String REGION = "region";
    public static final String DATA_CACHE_SIZE = "dataCacheSize";
    public static final String TIMEOUT = "timeout";
    public static final String WAIT_TIME = "waitTime";
    public static final String NAME_SERVER_LIST = "nameServerList";
    public static final String ROCKETMQ_PULL_FROM = "rocketmqpullfrom";
    public static final String ROCKETMQ_PULL_FROM_Time = "rocketMQPullFromTime";
    
    public static MetaStoreManager metaStoreManager = null;
    public static final String Table2MqRule = "table2MqRule";
    
    public static String TABLEKEY = "tableKey";
    public static HashMap<String, String> TABLE_KEY = new HashMap<String, String>();
    public static HashMap<String, Table2MQRule> UPDATE_FORWARDMQ = new HashMap<String, Table2MQRule>();
    public static HashMap<String, HashMap<String, REFieldType>> ROCKETMQ_DOC_DESC = new HashMap<String, HashMap<String, REFieldType>>();
    
    public static final String GET_CASSCOLUMNS = "getCassColumns";
    public static HashMap<String, HashMap<String, String>> TABLE_CR_COLUMNS = new HashMap<String, HashMap<String, String>>();
    public static HashMap<String, HashMap<String, String>> TABLE_RC_COLUMNS = new HashMap<String, HashMap<String, String>>();
    private static org.apache.log4j.Logger logger = Logger.getLogger(RuntimeEnv.class.getName());
    
    public static boolean initialize(Configuration pConf) throws REConnectionException, RESessionException {
        
        if (pConf == null) {
            logger.error("configuration object is null");
            return false;
        }
        conf = pConf;
        metaStoreManager = MetaStoreManager.getMetaStoreManger(pConf);
        if (metaStoreManager == null) {
            return false;
        }
        getConfAndSaveAsString(REGION);
        getConfAndSaveAsInteger(DATA_CACHE_SIZE);
        getConfAndSaveAsInteger(TIMEOUT);
        getConfAndSaveAsInteger(WAIT_TIME);
        getConfAndSaveAsString(NAME_SERVER_LIST);
        getConfAndSaveAsString(ROCKETMQ_PULL_FROM, true);
        getConfAndSaveAsString(ROCKETMQ_PULL_FROM_Time, true);
        getConfAndSaveAsString(GET_CASSCOLUMNS, true);
        
        if (RuntimeEnv.getParamAsString(GET_CASSCOLUMNS) != null) {
            try {
                String[] mongodbcolumns = RuntimeEnv.getParamAsString(GET_CASSCOLUMNS).split("[#]");
                for (int i = 0; i < mongodbcolumns.length; i++) {
                    HashMap<String, String> gettable = new HashMap<String, String>();
                    HashMap<String, String> gettable2 = new HashMap<String, String>();
                    String[] table2 = mongodbcolumns[i].split("[;]");
                    String[] columns = table2[1].split("[:]");
                    for (int k = 0; k < columns.length; k++) {
                        String[] col = columns[k].split(",");
                        gettable.put(col[0], col[1]);
                        gettable2.put(col[1], col[0]);
                    }
                    TABLE_CR_COLUMNS.put(table2[0], gettable);
                    TABLE_RC_COLUMNS.put(table2[0], gettable2);
                }
                
            } catch (Exception E) {
                logger.error(E);
                System.exit(0);
            }
            logger.info("LoadConfTablesDesc   is " + JSONObject.toJSONString(TABLE_CR_COLUMNS));
        }
        
        getConfAndSaveAsString(Table2MqRule, true);
        getConfAndSaveAsString(TABLEKEY, true);
        if (RuntimeEnv.getParam(TABLEKEY) != null && (!RuntimeEnv.getParam(TABLEKEY).equals(""))) {
            String[] tks = RuntimeEnv.getParamAsString(TABLEKEY).split(";");
            for (String tk : tks) {
                String[] ttt = tk.split(":");
                if (ttt.length == 2) {
                    TABLE_KEY.put(ttt[0], ttt[1]);
                } else {
                    logger.error("TableKey" + RuntimeEnv.getParamAsString(TABLEKEY) + " " + tk);
                    System.exit(0);
                }
            }
        }
        logger.info("Table_Key "+TABLE_KEY.toString());
        if (RuntimeEnv.getParam(Table2MqRule) != null && (!RuntimeEnv.getParam(Table2MqRule).equals(""))) {
            String[] tables2mqrule = RuntimeEnv.getParamAsString(Table2MqRule).split("[#]");
            for (int i = 0; i < tables2mqrule.length; i++) {
                String[] table2mq = tables2mqrule[i].split("[|]");
                if (table2mq.length == 5) {
                    Table2MQRule t2mr = new Table2MQRule(table2mq[0], table2mq[1], table2mq[2], table2mq[3], table2mq[4]);
                    UPDATE_FORWARDMQ.put(table2mq[0], t2mr);
                } else {
                    logger.error("single table2MqRule Size is not 5");
                    return false;
                }
            }
        }
        return true;
    }
    
    public static void dumpEnvironment() {
        conf.dumpConfiguration();
    }
    
    public static void addParam(String pParamName, Object pValue) {
        synchronized (dynamicParams) {
            dynamicParams.put(pParamName, pValue);
        }
    }
    
    public static Object getParam(String pParamName) {
        return dynamicParams.get(pParamName);
    }
    
    public static boolean getConfAndSaveAsString(String confName, Boolean isempty) {
        String tmp = conf.getString(confName, "");
        if (!isempty) {
            if (tmp.isEmpty()) {
                logger.error("parameter" + confName + "does not exist or is not defined");
                return false;
            }
        }
        dynamicParams.put(confName, tmp);
        logger.info(confName + ":" + tmp);
        return true;
    }
    
    public static boolean getConfAndSaveAsInteger(String confName) {
        String tmp = conf.getString(confName, "");
        if (tmp.isEmpty()) {
            logger.error("parameter " + confName + " does not exist or is not defined");
            return false;
        }
        try {
            dynamicParams.put(confName, Integer.parseInt(tmp));
            logger.info(confName + ":" + tmp);
        } catch (Exception ex) {
            logger.error("parameter " + confName + " 's format is wrong for " + ex.getMessage(), ex);
            return false;
        }
        return true;
    }
    
    public static boolean getConfAndSaveAsString(String confName) {
        String tmp = conf.getString(confName, "");
        if (tmp.isEmpty()) {
            logger.error("parameter" + confName + "does not exist or is not defined");
            return false;
        }
        dynamicParams.put(confName, tmp);
        logger.info(confName + ":" + tmp);
        return true;
    }
    
    public static boolean getConfAndSaveAsBoolean(String confName) {
        String tmp = conf.getString(confName, "");
        if (tmp.isEmpty()) {
            logger.error("parameter " + confName + " does not exist or is not defined");
            return false;
        }
        try {
            dynamicParams.put(confName, Boolean.parseBoolean(tmp));
            logger.info(confName + ":" + tmp);
        } catch (Exception ex) {
            logger.error("parameter " + confName + " 's format is wrong for " + ex.getMessage(), ex);
            return false;
        }
        return true;
    }
    
    public static String getParamAsString(String pParamName) {
        return (String) dynamicParams.get(pParamName);
    }
    
    public static Integer getParamAsInteger(String pParamName) {
        return (Integer) dynamicParams.get(pParamName);
    }
    
    public static Boolean getParamAsBoolean(String pParamName) {
        return (Boolean) dynamicParams.get(pParamName);
    }
}
